import Cookies from 'js-cookie'
import userApi from '@/api/user'
// initial state
const state = {
  userName: Cookies.get('UserName'),
  userInfo: Cookies.get('UserInfo') ? JSON.parse(Cookies.get('UserInfo')) : null,
  userRole: Cookies.get('UserRole') ? parseInt(Cookies.get('UserRole')) : null
}

// actions
const actions = {
  initUserInfo ({ commit }) {
    return userApi.getCurrentUser().then(re => {
      commit('setUserInfo', re.response)
      // 单独设置用户角色
      if (re.response && re.response.role) {
        commit('setUserRole', re.response.role)
      }
      return re.response
    })
  }
}

// mutations
const mutations = {
  setUserName (state, userName) {
    state.userName = userName
    Cookies.set('UserName', userName, { expires: 30 })
  },
  setUserInfo: (state, userInfo) => {
    state.userInfo = userInfo
    Cookies.set('UserInfo', JSON.stringify(userInfo), { expires: 30 })
  },
  setUserRole: (state, role) => {
    state.userRole = role
    Cookies.set('UserRole', role.toString(), { expires: 30 }) // 设置角色到Cookie
  },
  clearLogin (state) {
    state.userName = null
    state.userInfo = null
    state.userRole = null
    Cookies.remove('UserName')
    Cookies.remove('UserInfo')
    Cookies.remove('UserRole')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
